package org.kumas.bigdata.hdfs3.fsdirectory;

import java.util.Objects;

/*************************************************
 * TODO_Kumas
 *  Author： KumasZhang
 *  DateTime： 2021-12-02 8:49
 *  Description： 节点抽象
 **/
public class INode {
    private INode parent = null;
    private String absolutePath;

    String name;
    public INode(String name,INode parent) {
        this.parent = parent;
        this.name = name;
        setAbsolutePath((parent == null ? "/" : parent.getAbsolutePath() + "/" + name).replace("//", "/"));
    }

    public String getAbsolutePath() {
        return absolutePath;
    }

    INodeDirectory getParent() {
        return this.parent == null ? null : parent.asDirectory();
    }
    void setParent(INodeDirectory parent) {
        this.parent = parent;
        setAbsolutePath(parent.getAbsolutePath() + "/" + name);
    }

    private void setAbsolutePath(String absolutePath) {
        this.absolutePath = absolutePath.replace("//", "/");
    }

    public boolean isDirectory() {
        return false;
    }

    public boolean isFile() {
        return false;
    }


    INodeFile asFile() {
        throw new IllegalStateException("Current inode is not a file: " + this.getAbsolutePath());
    }

    public INodeDirectory asDirectory() {
        throw new IllegalStateException("Current inode is not a directory: " + this.getAbsolutePath());
    }


    @Override
    public String toString() {
        return getAbsolutePath();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null) return false;
        return Objects.equals(getAbsolutePath(), ((INode) o).getAbsolutePath());
    }

    @Override
    public int hashCode() {
        return Objects.hash(parent, name);
    }

}
